package com.example.qqfake;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CacheActivity extends AppCompatActivity {
    private final String serverAddress = "192.168.104.215";
    private final int serverPort = 50000;

    public  Socket socket;
    private PrintWriter out;
    private BufferedReader in;


    public String chat_name;
    public String chat_id;
    public String my_id;
    private List<Chat_content> list = new ArrayList<>();
    private Adapter3 adapter = new Adapter3(list);

    private ImageView exit_here;


    private EditText content_cache;
    private Button send_cache;
    private int i=0; //记录一下发送条数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_cache);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //获取intent中传递的消息
        Intent intent = getIntent();
        chat_name = intent.getStringExtra("chat_name");
        chat_id = intent.getStringExtra("chat_partner");

        // 从share中获取user_id
        // 获取SharedPreferences实例，文件名为"myPreferences"，与LoginActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
        // 读取数据，键为"User_id"
        my_id = sharedPreferences.getString("User_id","");



        //绑定控件
        content_cache = findViewById(R.id.content_cache);
        send_cache = findViewById(R.id.send_cache);
        exit_here = findViewById(R.id.exit_here);


        exit_here.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(CacheActivity.this,"存储成功",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(CacheActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });



        //点击事件：
        send_cache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                String message = "11,"+my_id+","+formattedString+","+content_cache.getText().toString()+","+chat_id;

                Thread thread = new Thread(new Worker(message));
                thread.start();
                //此处图片需要读取数据库中的头像
                Chat_content p1 = new Chat_content(1,content_cache.getText().toString(),R.drawable.right);
                // 通知适配器新元素添加
                adapter.addItem(p1);
                i++;
                content_cache.setText("");


            }
        });


        RecyclerView recyclerView = findViewById(R.id.rv3);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(linearLayoutManager);


        adapter = new Adapter3(list);
        recyclerView.setAdapter(adapter);






        //子线程开启socket发送连接请求，不停监听信息
        new Thread(()->{
            try {
                socket= new Socket(serverAddress, serverPort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out= new PrintWriter(socket.getOutputStream(), true);
                //给服务器发送一条在线提示

                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                String message = "8,"+my_id+","+formattedString+","+my_id+"online"+","+my_id;
                out.println(message);


                // 启动读取消息的线程
                //new Thread(this::readMessages).start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }).start();




    }

    public class Worker implements Runnable {
        private String message;
        public Worker(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            // 使用传递的消息

            out.println(message);

        }
    }


//    private void readMessages() {
//        try {
//            String message;
//            while ((message = in.readLine()) != null) {
//                if (!isFinishing()) {
//                    runOnUiThread(new Runnable() {//此run方法将由主线程运行
//                        @Override
//                        public void run() {
//                            Toast.makeText(CacheActivity.this,"存储成功",Toast.LENGTH_LONG).show();
//                        }
//                    });
//                }
//                break;
//
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}